<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="isUpdate ? t('action.edit') : t('action.create')"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :okText="t('action.save')"
    defaultFullscreen
    destroyOnClose
  >
    <BasicForm @register="registerForm">
      <template #multiSpecSlot="space">
        <!-- {{space}} -->
        <a-row>
          <a-col span="12" style="padding-right: 58px">
            <JDictSelectTag
              v-model:value="multiSpecId"
              type="select"
              dictCode="product_multi_spec,name,id"
              placeholder="请选择下拉"
              @change="changeMultiSpec"
            />
          </a-col>
        </a-row>
        <SkuForm ref="skuFormRef" :sourceAttribute="sourceAttribute" v-model:attribute="attribute" v-model:sku="sku" />
      </template>
      <template #action="{ record }">
        <TableAction :actions="skuRowAction(record)" />
      </template>
    </BasicForm>
    <template #appendFooter>
      <a-button type="primary" @click="saveAndNext" :disabled="loading">{{ t('action.saveAndNext') }}</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref, watch, reactive } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  // import { BasicTable, useTable, TableAction } from '/@/components/Table';
  // import { JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { formSchema, sourceAttribute, attribute, sku, multiSpecId, spuId } from './spu.data';
  import { saveOrUpdate, getMultiSpecChildren, getSkusById } from './spu.api';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import SkuForm from '/@/views/goods/spu/SkuForm.vue';
  defineOptions({ name: 'SpuModal' });

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const skuFormRef = ref();
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: { span: 23 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    multiSpecId.value = '';
    if (unref(isUpdate)) {
      setFieldsValue({ ...data?.record });
      // 回显子表数据
      multiSpecId.value = data?.record?.multiSpecId;
      spuId.value = data?.record?.id;
      changeMultiSpec(multiSpecId.value);
    }
  });

  function skuRowAction(record) {
    return [
      {
        label: t('action.delete'),
        onClick: handleSkuEdit.bind(null, record),
      },
    ];
  }

  function handleSkuEdit(record) {
    console.log(record);
  }

  async function getSkuData() {
    let skuDataValid = true;
    let skuData: Recordable[] = [];
    if (!skuDataValid) {
      throw { errorFields: [{ name: ['skus'] }] };
    }
    return skuData;
  }

  /**
   * 保存并继续
   */
  function saveAndNext() {
    handleSubmit(false);
  }

  /**
   * @param data 成功后是否关闭弹框,默认值:true
   */
  async function handleSubmit(data) {
    try {
      const values = await validate();
      if (sku.value.length <= 0) {
        createMessage.success('请选择规格');
        return;
      }

      if (multiSpecId.value !== '' && multiSpecId.value !== null) {
        sku.value.forEach((item) => {
          if (item.salePrice === '') {
            createMessage.success('请输入规格价格，不能为空');
            throw new Error('请输入规格价格，不能为空');
          }
          if (item.totalNum === '') {
            createMessage.success('请输入规格库存，不能为空');
            throw new Error('请输入规格库存，不能为空');
          }
        });
      }
      values.multiSpecId = multiSpecId.value;
      values.skus = sku.value;
      setModalProps({ confirmLoading: true });
      await saveOrUpdate(values, isUpdate.value);
      if (data) {
        closeModal();
        sourceAttribute.value = [];
      } else {
        resetFields();
        sourceAttribute.value = [];
      }
      emit('success');
      createMessage.success(t('common.saveSuccessText'));
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  const changeMultiSpec = async (value) => {
    const data = await getMultiSpecChildren(value);
    const res = await getSkusById(spuId.value, {});
    if (res.specs) {
      attribute.value = res.specs;
    }
    if (res.skus) {
      res.skus.forEach((item) => {
        item.specName = item.specNameStr;
      });
      sku.value = res.skus;
    }

    sourceAttribute.value.splice(0, sourceAttribute.value.length);
    data?.forEach((item) => {
      const itemData: any = [];
      item?.children.forEach((children) => {
        itemData.push(children?.name);
      });
      item.item = itemData;
      sourceAttribute.value.push(item);
    });
  };
  function handleCancel() {
    closeModal();
    sourceAttribute.value = [];
    attribute.value = [];
    sku.value = [];
  }
</script>
